package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.StationService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenm
 * @create 2019-07-13 14:34
 */
@Service("stationService")
public class StationServiceImpl implements StationService {

    private static final Logger logger = LoggerFactory.getLogger(StationServiceImpl.class);

    @Resource
    private StationMapper stationMapper;

    @Resource
    private ProductlineMapper productLineMapper;


    @Resource
    private ProStationMapper proStationMapper;

    @Resource
    private FixedDeteMapper fixedDeteMapper;
    @Resource
    private UploadMapper uploadMapper;

    @Resource
    private DeviceMapper deviceMapper;

    /**
     * 新增
     *
     * @param station
     * @return
     */
    @Override
    public JSONObject insertStation(Station station) {
        try {
            if (station.getStationId() != null) {
                throw new ParamsErrorException("新增操作不能选择工位");
            }
            //获取到车间ID
            //通过产品线获取
            Integer productionLineId = station.getProductlineId();
            if ("".equals(productionLineId) || productionLineId == null) {
                return JSONObject.build(403, "产线id为空");
            }
            List<Productline> productLine = productLineMapper.queryByProductLineId(productionLineId);
            if (productLine.isEmpty()) {
                throw new ModifyFailedException("产线不存在");
            }
            Integer workshopId = productLine.get(0).getWorkshopId();
            station.setWorkshopId(workshopId);
            checkParam(station);
            checkNoRepate(station);

            int row = stationMapper.insertSelective(station);
            if (row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 删除
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public JSONObject delStation(Integer[] staIds, Integer dataState) {
        try {
            if (dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            } else if (dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (staIds == null) {
                throw new ParamsErrorException("请选择要删除的工位");
            }
            if(dataState==2 || dataState==3){
               int deviceCount = deviceMapper.queryByStationIds(staIds);
                if(deviceCount>0){
                    if(dataState==2){
                        return JSONObject.build(400,"所选工位关联设备信息,删除失败");
                    }else{
                        return JSONObject.build(400,"所选工位关联设备信息,停用失败");
                    }
                }
                /*int proStationCount=proStationMapper.queryByStationIds(staIds);
                if(proStationCount>0){
                    if(dataState==2){
                        return JSONObject.build(400,"所选工位关联工序信息,删除失败");
                    }else{
                        return JSONObject.build(400,"所选工位关联工序信息,停用失败");
                    }
                }*/
                int fixedDeteCount=fixedDeteMapper.queryByStationIds(staIds);
                if(fixedDeteCount>0){
                    if(dataState==2){
                        return JSONObject.build(400,"所选工位关联固定检测项目信息,删除失败");
                    }else{
                        return JSONObject.build(400,"所选工位关联固定检测项目信息,停用失败");
                    }
                }
            }
            // 执行存储过程
            int row = stationMapper.delStation(staIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";
                        break;
                    case 2:
                        msg = "删除成功";
                        break;
                    case 3:
                        msg = "停用成功";
                        break;
                    default:
                }
            }
           int proStationCount = proStationMapper.updateProStationByStaId(staIds, dataState);
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 修改
     *
     * @param station
     * @return
     */
    @Override
    public JSONObject updateStation(Station station) {
        try {
            if (station.getStationId() == null) {
                throw new ParamsErrorException("请选择要修改的工位资料");
            }
            //通过产品线获取
            Integer productionLineId = station.getProductlineId();
            if (productionLineId == null || "".equals(productionLineId)) {
                throw new ModifyFailedException("产线id为空");
            }
            List<Productline> productLine = productLineMapper.queryByProductLineId(productionLineId);
            if (productLine.size() == 0 || productLine.isEmpty()) {
                throw new ModifyFailedException("产线不存在");
            }
            Integer workshopId = productLine.get(0).getWorkshopId();

            station.setWorkshopId(workshopId);
            checkParam(station);
            checkNoRepate(station);
            int row = stationMapper.updateByPrimaryKeySelective(station);

            if (row == 0) {
                throw new ModifyFailedException("数据更新失败");
            }
            return JSONObject.oK("更新成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 查询
     *
     * @param station
     * @return
     */
    @Override
    public JSONObject queryStation(Station station) {
        List<Station> liststStations = null;
        try {
            Integer pagesize = station.getPagesize();
            Integer pageindex = station.getPageindex();
            if (pagesize != null && pageindex != null) {
                station.setIncept(pagesize * (pageindex - 1));
            }
            /*Integer lProductLineId = station.getStaId();
            if(lProductLineId != null) {  //如果有id,则查询单个产线信息
                liststStations = stationMapper.getStation(lProductLineId);
            } else{  //查询多个sop管理信息

            }*/
            liststStations = stationMapper.listStation(station);
            if (liststStations.isEmpty()) {
                return JSONObject.oK("没有产线相关数据", liststStations, 0);
            }
            //查询分页总记录数
            int count = stationMapper.countStation(station);
            return JSONObject.oK("查询成功", liststStations, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 根据编码查重
     *
     * @param staCode
     * @param staId
     * @return
     */
    @Override
    public Station getByStationCode(String staCode, Integer staId) {
        // TODO Auto-generated method stub
        return stationMapper.getByStationCode(staCode, staId);
    }


    /**
     * 根据产线查询工位集合
     *
     * @param productionLineId
     * @return
     */
    @Override
    public List<Station> getByProductionLineId(Integer productionLineId) {
        // TODO Auto-generated method stub
        return stationMapper.getByProductionLineId(productionLineId);
    }

    /**
     * 根据车间查询工位集合
     *
     * @param workShopId
     * @return
     */
    @Override
    public List<Station> getByWorkshopId(Integer workShopId) {
        // TODO Auto-generated method stub
        return stationMapper.getByWorkshopId(workShopId);
    }


    /**
     * 根据工序查询工位集合
     *
     * @param proId
     * @return
     */
    @Override
    public List<Station> getByProId(Integer proId) {
        // TODO Auto-generated method stub
        return stationMapper.getByProId(proId);
    }


    /**
     * 信息验证
     *
     * @param station
     * @return
     */
    private void checkParam(Station station) {
        if (StringUtils.isEmpty(station.getStationCode())) {
            throw new ParamsErrorException("工位编码不能为空");
        }
        if (station.getStationCode().length() > 50) {
            throw new ParamsErrorException("工位编码长度不能大于50");
        }
        if (getByStationCode(station.getStationCode(), station.getStationId()) != null) {
            throw new ParamsErrorException("工位编码已存在");
        }
        if (StringUtils.isEmpty(station.getStationName())) {
            throw new ParamsErrorException("工位名称不能为空");
        }
        if (station.getStationTypeId() == null) {
            throw new ParamsErrorException("工位类型不能为空");
        }
        if ("".equals(station.getWorkshopId()) || station.getWorkshopId() == null) {
            throw new ParamsErrorException("所选产线没有车间");
        }
        if (station.getStationName().length() > 50) {
            throw new ParamsErrorException("工位名称的长度不能大于50");
        }
        if (station.getProductlineId() == null) {
            throw new ParamsErrorException("请选择所属产线");
        }
        if (station.getRemark().length() > 100) {
            throw new ParamsErrorException("备注说明的长度不能大于100");
        }


    }

    /**
     * 根据名称去重
     */
    private void checkNoRepate(Station station) {
        int count = stationMapper.selectByStaName(station);
        if(count>0){
            throw new ParamsErrorException("工位名称已存在");
        }
    }

    /**
     * @author: louk
     * @Description: 删除工序信息下的工位
     * @date: 2019/9/5 14:27
     */

    @Override
    public JSONObject delStationByPro(Long[] staIds) {

        try {

            if (staIds == null) {
                throw new ParamsErrorException("请选择要删除的工位");
            }
            int row = stationMapper.deleteStationByPro(staIds);
            if (row == 0) {
                throw new ParamsErrorException("工位删除失败");
            }
            return JSONObject.oK("删除成功");

        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 检查excel内容
     * @param station
     * @return
     */
    @Override
    public String checkExcelContent(Station station) {
        //判断当前行内容是否为空/不存在
        if (StringUtils.isBlank(station.getStationCode()) && StringUtils.isBlank(station.getStationName()) && StringUtils.isBlank(station.getStationTypeName()) &&
                StringUtils.isBlank(station.getRemark()) && StringUtils.isBlank(station.getProductlineName())) {
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if (StringUtils.isEmpty(station.getStationCode())) {
            return "工位编码为空";
        }
        if (station.getStationCode().getBytes().length > 50) {
            return "工位编码长度大于50个字节,25个汉字";
        }
        if (stationMapper.checkNoRepeatStaCode(station) > 0) {
            return "工位编码已存在";
        }
        if (StringUtils.isEmpty(station.getStationName())) {
            return "工位名称为空";
        }
        if (stationMapper.checkNoRepeatStaName(station) > 0) {
            return "工位名称已存在";
        }
        if (station.getStationTypeName() == null) {
            return "工位类型为空";
        }
        Map<String, Datadict> tdatadictMap = uploadMapper.queryType(101039);
        if (!tdatadictMap.containsKey(station.getStationTypeName())) {
            return "工位类型输入错误/不规范";
        } else {
            Datadict tdatadict = tdatadictMap.get(station.getStationTypeName());
            station.setStationTypeId(tdatadict.getItemId());
        }
        if (station.getStationName().getBytes().length > 50) {
            return "工位名称的长度不能大于50个字节,25个汉字";
        }
        if (StringUtils.isBlank(station.getProductlineName())) {
            return "所属产线为空";
        }
        Map<String, Productline> productLineMap = uploadMapper.queryProductionLine();
        if (!productLineMap.containsKey(station.getProductlineName())) {
            return "所属产线输入错误/不规范";
        } else {
            station.setProductlineId(productLineMap.get(station.getProductlineName()).getProductlineId());
            //获取到车间ID
            //通过产品线获取
            Integer productionLineId = station.getProductlineId();
            List<Productline> productLine = productLineMapper.queryByProductLineId(productionLineId);
            Integer workshopId = productLine.get(0).getWorkshopId();
            station.setWorkshopId(workshopId);
        }
        if (station.getRemark() != null && station.getRemark().getBytes().length > 100) {
            return "备注说明的长度不能大于100个字节,50个汉字";
        }
        return null;
    }

    @Override
    public JSONObject updateListStation(List<Station> stationList) {
        if (!stationList.isEmpty()) {
            int updateNum = uploadMapper.updateListStation(stationList);
            if (updateNum > 0) {
                return JSONObject.build(JSONObject.SUCCESS, "导入成功", updateNum);
            } else {
                return JSONObject.build(JSONObject.ERROR, "导入失败", updateNum);
            }
        }
        return JSONObject.build(JSONObject.SUCCESS, "导入成功", null);
    }


    /**
     * 去添加查询（产品，任务单，批次）
     */
    @Override
    public JSONObject queryListStationToInsert(Station station) {
        try {
            //获取页面的数据个数
            Integer pagesize = station.getPagesize();
            //获取查询的页数
            Integer pageindex = station.getPageindex();
            if (pagesize != null && pageindex != null) {
                station.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<Station> stationList = stationMapper.queryListStationToInsert(station);

            //如果页数和页面数量都不为空的情况下进行计数
            if (stationList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, stationList, 0);
            } else {
                Integer count = stationMapper.countStationToInsert(station);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, stationList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }

    @Override
    public JSONObject treeStation() {
        List<Tree> workShopTreeList = uploadMapper.queryWorkShopXTreeNode();
        List<Tree> productLineTreeList = uploadMapper.queryProductlineXTreeNode();
        Map<Object,List<Tree>> workshopIdProductLineTreeListMap=new HashMap<>();
        transformMap(productLineTreeList,workshopIdProductLineTreeListMap);
        List<Tree> stationTreeListNode = uploadMapper.queryStationXTreeNode();
        Map<Object,List<Tree>> productLineIdStationTreeListMap=new HashMap<>();
        transformMap(stationTreeListNode,productLineIdStationTreeListMap);
        for (Tree tree : workShopTreeList) {
            List<Tree> productlineList = workshopIdProductLineTreeListMap.get(tree.getId());
            if(productlineList!=null && !productlineList.isEmpty()){
                for (Tree productLine : productlineList) {
                    productLine.setChildren(productLineIdStationTreeListMap.get(productLine.getId()));
                    productLine.setParent(true);
                }
                tree.setChildren(productlineList);
                tree.setParent(true);
            }
        }
        return JSONObject.oK("查询成功",workShopTreeList,workShopTreeList.size());
    }

    public void transformMap(List<Tree> treeList,Map<Object,List<Tree>> treeMap){
        for (Tree xTreeNode : treeList) {
            Object pId = xTreeNode.getpId();
            if(!treeMap.containsKey(xTreeNode.getpId())){
                treeMap.put(xTreeNode.getpId(),new ArrayList<>());
            }
            treeMap.get(pId).add(xTreeNode);
        }
    }
}
